<template>
    <div class="mainBox">
        <PageHeaderNav :need-underline="false" content="用药提醒" :need-back="false"></PageHeaderNav>
        <div class="content">
            <van-cell
                class="btnFocus speech"
                :title="`${currentDate.getFullYear()}-${currentDate.getMonth() + 1}-${currentDate.getDate()}`.replace(/\b(\w)\b/g, '0$1')"
                @click="showCalendar = true"
            />
            <van-calendar
                v-model="showCalendar"
                :default-date="currentDate"
                :show-confirm="false"
                :min-date="minDate"
                :max-date="maxDate"
                :color="calendarColor"
                @confirm="selectDateEvent"
            />
            <div class="confArea">
                <div class="btnFocus speech" v-for="conf in confList">
                    <router-link :to="conf.toRouter">
                        <img :src="conf.img" alt="">
                        <span>{{ conf.text }}</span>
                    </router-link>
                </div>
                <div class="btnFocus speech">
                    <a @click="medicineRecordEvent">
                        <img src="@/assets/images/medicineClockView/medicinelist.png" alt="">
                        <span>用药记录</span>
                    </a>
                </div>
            </div>
            <div class="block">
                <el-timeline>
                    <el-timeline-item
                        v-for="(remindItemList, timeStamp) in remindItemListGroup"
                        :key="'timeline-item' + timeStamp"
                        :color="calendarColor"
                        size="large"
                    >
                        <MedicineReminder
                            ref="MedicineReminder"
                            :time-stamp="timeStamp"
                            :remind-item-list="remindItemList"
                            :current-date="currentDate"
                            @takeMedicine="takeMedicine"
                            :key="timeStamp"
                        />
                    </el-timeline-item>
                </el-timeline>
            </div>
            <el-empty v-if="!Boolean(Object.keys(remindItemListGroup).length)"
                      description="今天没有服药提醒，尽情享受生活吧"></el-empty>
        </div>
    </div>
</template>
<script>
import MedicineReminder from '@/components/MedicineClock/MedicineReminder.vue';
import PageHeaderNav from "@/components/Publlic/PageHeaderNav.vue";

export default {
    components: {
        MedicineReminder,
        PageHeaderNav
    },

    data() {
        return {
            /* 原始数据：选中日期的用于API传输的约定Json格式数据 */
            currentDateApiMedicineList: [],

            /* 日历 */
            // 显示或隐藏日历
            showCalendar: false,
            // 选中的日期
            currentDate: new Date(new Date().setHours(0, 0, 0, 0)),
            // 日历的主题色
            calendarColor: this.$(":root").css("--color"),
            // 日历的日期选择范围
            minDate: new Date(2023, 1, 1),
            maxDate: new Date(new Date().getFullYear() + 10, 1, 1),

            /* 功能区 */
            confList: [
                {
                    img: require("@/assets/images/medicineClockView/medicinebottom.png"),
                    text: "添加提醒",
                    toRouter: "/medicineClockView/newMedicineView"
                },
                {
                    img: require("@/assets/images/medicineClockView/medicineadd.png"),
                    text: "用药管理",
                    toRouter: "/medicineClockView/manageMedicineView"
                }
            ]
        }
    },

    methods: {
        // 请求选中日期的药品提醒信息
        ApiGetCurrentDateMedicineList() {
            this.request.post("/medicineReminder/getCurrentDateMedicineList/", {
                currentTimeStamp: this.$public.dateToTimeStampString(this.currentDate)
            }).then((response) => {
                const status = response["code"] === 200

                if (status) {
                    // 回写数据
                    this.currentDateApiMedicineList = response["data"]["medicineList"]
                }
            })
        },

        // 选中日期事件
        selectDateEvent(date) {
            this.currentDate = date
            this.showCalendar = false

            // 请求该日期数据
            this.ApiGetCurrentDateMedicineList()
        },

        // 药品服用事件
        takeMedicine(remindItemId) {
            const nowTimeStamp = this.$public.dateToTimeStampString(this.currentDate)
            const todayFinishedTimeStampRecord = this.findTodayFinishedTimeStampRecordFromFinishedTimeStampRecordList(remindItemId, nowTimeStamp)
            let finishedTimeStampRecordList = this.findReminderItemFromCurrentDateApiMedicineListByReminderItemId(remindItemId).finishedTimeStampRecordList

            // 取消本次服药记录
            if (todayFinishedTimeStampRecord) {
                this.request.post("/medicineReminder/cancelFinishedRecord/", {
                    nowTimeStamp: nowTimeStamp,
                    remindItemId: remindItemId
                }).then((response) => {
                    const status = response["code"] === 200

                    if (status) {
                        // 数据库更新成功，本地数据更新同步
                        finishedTimeStampRecordList.splice(finishedTimeStampRecordList.indexOf(todayFinishedTimeStampRecord), 1)
                    }
                })
            }

            // 产生服药记录
            else {
                this.request.post("/medicineReminder/takeFinishedRecord/", {
                    nowTimeStamp: nowTimeStamp,
                    remindItemId: remindItemId
                }).then((response) => {
                    const status = response["code"] === 200

                    if (status) {
                        // 数据库更新成功，本地数据更新同步
                        finishedTimeStampRecordList.push(nowTimeStamp)
                    }
                })
            }
        },

        // 通过reminderItemId在currentDateApiMedicineList中寻找reminderItem项
        findReminderItemFromCurrentDateApiMedicineListByReminderItemId(reminderItemId) {
            return this.currentDateApiMedicineList.map(medicine => medicine.reminderItemList).flat().find(reminderItem => reminderItem.id === reminderItemId)
        },

        // 通过reminderItemId寻找某天的服药服药记录时间戳
        findTodayFinishedTimeStampRecordFromFinishedTimeStampRecordList(reminderItemId, finishedTimeStamp) {
            return this.findReminderItemFromCurrentDateApiMedicineListByReminderItemId(reminderItemId).finishedTimeStampRecordList.find(finishedTimeStampRecord => this.$public.twoTimeStampIsSameDay(finishedTimeStampRecord, finishedTimeStamp))
        },

        // 通过reminderItemId判断某天有没有服药
        todayIsFinished(reminderItemId, finishedTimeStamp) {
            return Boolean(this.findTodayFinishedTimeStampRecordFromFinishedTimeStampRecordList(reminderItemId, finishedTimeStamp))
        },

        medicineRecordEvent() {
            this.$message({
                message: '请选择查询日期',
                type: 'info'
            })
            this.showCalendar = true
        }
    },

    computed: {
        // 用药提醒数据集。组合提醒项，以时间戳作为Key
        remindItemListGroup() {
            // 组合提醒项，并过滤掉得到未完成服药和选中的日期的提醒项
            let reminderItemList = []
            const currentDateTimeStamp = this.$public.dateToTimeStampString(this.currentDate)
            this.currentDateApiMedicineList.filter(medicine => this.$public.isStartDateTimeStampBetweenEndDateTimeStamp(medicine.startDateTimeStamp, currentDateTimeStamp, medicine.endDateTimeStamp)).forEach(medicine => {
                const reminderItems = medicine.reminderItemList.map(reminderItem => {
                    return {
                        id: reminderItem.id,
                        name: medicine.name,
                        dosage: medicine.dosage,
                        timeStamp: reminderItem.timeStamp,
                        finished: this.todayIsFinished(reminderItem.id, currentDateTimeStamp),
                    }
                })
                reminderItemList.push(...reminderItems)
            })

            // 按时间戳分组
            let remindItemListGroup = {}
            reminderItemList.forEach(reminderItem => {
                const key = reminderItem["timeStamp"]
                if (!remindItemListGroup.hasOwnProperty(key)) return remindItemListGroup[key] = [reminderItem]
                remindItemListGroup[key].push(reminderItem)
            })

            // 将medicineRemindGroup按key（时间戳）进行排序
            let remindItemListGroupSort = {}
            let keyListSort = Object.keys(remindItemListGroup).sort()
            keyListSort.forEach(key => remindItemListGroupSort[key] = remindItemListGroup[key])
            return remindItemListGroupSort
        }
    },

    created() {
        // 初始化请求数据
        this.ApiGetCurrentDateMedicineList()
    }
}


</script>

<style lang="less" scoped>
.mainBox {
    height: 100%;
}

.content {
    height: calc(100% - 65px);
    background-color: var(--grayColor);
    overflow-y: scroll;
}

.van-cell {
    width: 50%;
    margin: auto;
    text-align: center;
    font-size: 1.3rem;
    font-weight: bold;
    color: white;
    background-color: rgba(var(--colorR), var(--colorG), var(--colorB), 0.7);
    border-bottom-left-radius: 10px;
    border-bottom-right-radius: 10px;
}

.confArea {
    box-sizing: border-box;
    margin: 15px;
    display: flex;
    justify-content: space-between;

    div {
        width: 32%;
        height: 60px;
        background-color: white;
        border-radius: 10px;
        box-sizing: border-box;
        font-size: 0.9rem;
        display: flex;
        align-items: center;

        a {
            text-align: center;
            display: flex;
            align-items: center;
            justify-content: center;
            color: black;
        }

        img {
            width: 22%;
            margin-right: 5px;
        }
    }
}

.block {
    box-sizing: border-box;
    padding: 15px;
}

::v-deep {
    .el-timeline-item, .el-timeline-item__wrapper, .el-timeline-item__content {
        width: 100%;
    }

    .el-timeline-item {
        display: flex;
        align-items: center;
        width: 100%;

        .el-timeline-item__tail {
            border-left: 4px solid white;
        }

        .el-timeline-item__wrapper {
            top: 0;
        }

        .el-timeline-item__timestamp.is-bottom {
            display: none;
        }
    }

    .el-timeline-item__node {
        left: -0.5px;
    }

    .el-timeline-item:first-child .el-timeline-item__tail:before {
        content: "";
        position: absolute;
        left: -4px;
        width: 4px;
        height: 50%;
        background-color: var(--grayColor)
    }

    .el-timeline-item:last-child .el-timeline-item__tail {
        display: block;
    }

    .el-timeline-item:first-child, .el-timeline-item:last-child {
        .el-timeline-item__tail:before {
            content: "";
            position: absolute;
            left: -4px;
            width: 4px;
            height: 50%;
            background-color: var(--grayColor)
        }
    }

    .el-timeline-item:last-child {
        .el-timeline-item__tail:before {
            top: 50%;
        }
    }
}
</style>